package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.feign.ArticleFeign;
import com.heima.article.entity.ApAuthor;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.MediaFeign;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-23
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private IApUserService apUserService;

    @Autowired
    private MediaFeign mediaFeign;

    @Autowired
    private ArticleFeign articleFeign;


    /**
     * 根据认证状态分页查询认证用户列表
     *
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult listByStatus(AuthDto authDto) {
        //1.封装查询条件 ： 状态
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, authDto.getStatus());
        }
        //2.封装分页信息
        IPage<ApUserRealname> iPage = new Page<>(authDto.getPage(), authDto.getSize());

        //3.执行分页查询
        iPage = this.page(iPage, queryWrapper);

        //4.封装响应数据
        PageResponseResult<List<ApUserRealname>> result = new PageResponseResult<>(authDto.getPage(), authDto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }


    /**
     * 审核通过/拒绝
     *
     * @param dto
     * @param type
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult auth(AuthDto dto, int type) {
        //审核通过
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (type == 1) {
            //1.根据提交实名认证用户ID 查询 实名认证记录  修改实名认证状态
            apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
            this.updateById(apUserRealname);

            //2.远程调用自媒体微服务，创建自媒体用户--自媒体用户相关信息从APP用户中获取
            //2.1 封装自媒体用户对象需要使用APP用户，根据APP用户ID查询APP用户信息
            ApUser apUser = apUserService.getById(apUserRealname.getUserId());
            //2.2 创建自媒体作者
            WmUser wmUser = createWmUser(apUser);

            //3.远程调用文章微服务，创建作者用户.修改 APP用户类型改为：自媒体用户
            if (wmUser != null) {
                //3.1 封装作者对象ApAuthor 新增作者用户 得到作者对象
                ApAuthor apAuthor = createApAuthor(apUser, wmUser);

                //3.2 远程调用自媒体微服务 更新 自媒体用户表中逻辑外键：作者ID
                if (apAuthor != null) {
                    wmUser.setApAuthorId(apAuthor.getId());
                    mediaFeign.updateWmUser(wmUser);
                    //3.3 更新APP用户表标记：自媒体用户  实名认证状态：true
                    apUser.setIsCertification(true);
                    apUser.setFlag(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
                    apUserService.updateById(apUser);
                }
            }
        } else {
            //审核失败
            apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_FAIL.getVal());
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);
        }
        return ResponseResult.okResult();
    }


    /**
     * 创建作者用户
     *
     * @param apUser APP用户信息
     * @param wmUser 自媒体作者信息
     * @return 新增后作者对象
     */
    private ApAuthor createApAuthor(ApUser apUser, WmUser wmUser) {
        //1.构建作者对象
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(UserEnum.AUTHOR_TYPE_WEMEDIA.getVal());
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());

        //2.远程调用文章微服务 完成新增作者
        ResponseResult<ApAuthor> responseResult = articleFeign.saveApAuthor(apAuthor);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            return responseResult.getData();
        }
        return null;
    }


    /**
     * 创建自媒体作者
     *
     * @param apUser APP用户信息
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1.封装自媒体用户对象
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        wmUser.setType(0);

        //2.远程调用自媒体微服务新增自媒体用户 TODO:新增后作者ID逻辑外键值为空
        ResponseResult<WmUser> responseResult = mediaFeign.saveWmUser(wmUser);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser data = responseResult.getData();
            return data;
        }
        return null;
    }
}
